<template>
  <div class="merak-container-has-aside" curPageName="7dsfds12312353123" v-loading="pageloading">
    <div class="merak-aside">

      <el-input style="margin-bottom: 15px" v-model="treeFilter" :placeholder="$t('merak.placeholder_filter')"
        @input="value => treeRef?.filter(value)" />
      <div class="tree-wrapper">
        <el-scrollbar>
          <!-- noCurCss -->
          <el-tree :class="curlevel > 2 ? 'merakTree' : 'merakTree '" ref="treeRef" node-key="id" :data="treedata"
            :default-expanded-keys="expandedKeys" :props="defaultProps" :default-checked-keys="curcheck_id"
            :highlight-current="true" :filter-node-method="(value, tree) => tree.label.includes(value)"
            @current-change="changeTreeFilter" />
        </el-scrollbar>
      </div>
    </div>

    <div class="merak-card merak-container-has-search" v-waterMarker >
      <div>
        <searchBar :close-plan="false" ref="searchbar" :placeholder='$t("goods_document.goods_certify_no")' :close-advanced="false"
          :search_val="search_val" @search-event="searchBarPost" v-model="searchform">

          <!-- 高级搜索弹出框 插槽-->
          <template #searchForm="searchProp">

            <!--  高级搜索弹出框内容-->
            <div class="modal-content">
              <!-- 高级搜索 -->
              <div class="modal-title">

              </div>

              <div class="modal—body">
                <el-scrollbar class="search_from_scrollbar" height="100%">
                  <div class="scrollbar-content">
                    <!-- 已选参数 组件-->
                    <selectedParams class="" v-model="searchform" label="label" val="value" option-key="options">
                    </selectedParams>


                    <!-- 表单 -->
                    <el-form :model="searchform" :rules="searchformRules" label-position="top" ref="searchFormRef">

                      <el-row :gutter="40">
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <!-- 注册编号 -->
                          <el-form-item :label='$t("goods_document.goods_certify_no")' prop="employee_name.value">
                            <el-input class="qf_input" v-model="searchform.goods_certify_no.value" />
                          </el-form-item>
                        </el-col>


                        <!-- 单证类型 -->
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.goods_certify_type")'>
                            <el-select :loading="optionloading"
                              @visible-change="handleVisibleChange(searchform.goods_certify_type.options, 'goods_certify_type')"
                              class="qf_select" v-model="searchform.goods_certify_type.value"
                              :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.goods_certify_type.options" :key="item.value"
                                :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>

                        <!-- 进口公司 -->
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.apply_name_factory")'>
                            <el-select :loading="optionloading"
                              filterable
                              @visible-change="handleVisibleChange(searchform.apply_name_factory.options, 'apply_name_factory')"
                              class="qf_select" v-model="searchform.apply_name_factory.value"
                              :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.apply_name_factory.options" :key="item.value"
                                :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>

                          <!-- 单证状态 -->
                          <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.invalid")'>
                            <el-select :loading="optionloading"
                              @visible-change="handleVisibleChange(searchform.invalid.options, 'invalid')"
                              class="qf_select" v-model="searchform.invalid.value"
                              :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.invalid.options" :key="item.value"
                                :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>


                         <!-- 系统品牌-->
                         <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.brand")'>
                            
                            <el-select filterable :loading="optionloading"
                            
                              @visible-change="handleVisibleChange(searchform.brand.options, 'brand')" class="qf_select"
                              v-model="searchform.brand.value" :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.brand.options" :key="item.value" :label="item.label"
                                :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>


                          <!-- 其他品牌 -->
                          <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.other_brands")'>
                            <el-input class="qf_input" v-model="searchform.other_brands.value" />
                          </el-form-item>
                        </el-col>






                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item  :label='$t("goods_document.period_date_valid")'>

                            <el-date-picker v-model="rangeTimeOne" type="daterange"
                              :range-separator="$t('merak.rangto')"
                              :start-placeholder='$t("goods_document.start_date")'
                              :end-placeholder='$t("goods_document.end_date")' class="qf_date"
                              @change="dataPost(rangeTimeOne, 'daterang')" :format="format" value-format="YYYY-MM-DD" />
                          </el-form-item>
                        </el-col>





                        <!-- 商品描述 -->
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.product_description")'>
                            <el-input class="qf_input" v-model="searchform.product_description.value" />
                          </el-form-item>
                        </el-col>


                           <!-- 年龄 -->
                           <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.adult_child")'>
                            <el-select :loading="optionloading"
                              @visible-change="handleVisibleChange(searchform.adult_child.options, 'adult_child')"
                              class="qf_select" v-model="searchform.adult_child.value"
                              :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.adult_child.options" :key="item.value"
                                :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>



                        <!-- 申请人-->
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.apply_type")'>
                            <el-select :loading="optionloading"
                              @visible-change="handleVisibleChange(searchform.apply_type.options, 'apply_type')"
                              class="qf_select" v-model="searchform.apply_type.value"
                              :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.apply_type.options" :key="item.value"
                                :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>



                        
                        <!-- 中国公司-->
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.factoy")'>
                            <el-select :loading="optionloading"
                            filterable
                              @visible-change="handleVisibleChange(searchform.factoy.options, 'factoy')"
                              class="qf_select" v-model="searchform.factoy.value"
                              :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.factoy.options" :key="item.value" :label="item.label"
                                :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>



                        
                        <!-- 商家-->
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.supplier_id")'>
                            <el-select filterable :loading="optionloading"
                              
                              @visible-change="handleVisibleChange(searchform.supplier_id.options, 'supplier_id')"
                              class="qf_select" v-model="searchform.supplier_id.value"
                              :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.supplier_id.options" :key="item.value"
                                :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>





                        
                        <!-- 商品类型-->
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.type_id")'>
                            <el-select :loading="optionloading"
                              @visible-change="handleVisibleChange(searchform.type_id.options, 'type_id')"
                              class="qf_select" v-model="searchform.type_id.value"
                              :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.type_id.options" :key="item.value"
                                :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>




                      















                     


                      


                     







                        <!-- 创建人-->
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.created_by")'>
                            <el-select :loading="optionloading"
                              @visible-change="handleVisibleChange(searchform.created_by.options, 'created_by')"
                              class="qf_select" v-model="searchform.created_by.value"
                              :placeholder='$t("merak.placeholder_select")'>
                              <el-option v-for="item in searchform.created_by.options" :key="item.value"
                                :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>




                        
                        <el-col :span="lang == 'ru' ? 8 : 6">
                          <el-form-item :label='$t("goods_document.create_time")'>

                            <el-date-picker v-model="rangeTimeTwo" type="daterange"
                              :range-separator="$t('merak.rangto')"
                              :start-placeholder='$t("goods_document.create_start")'
                              :end-placeholder='$t("goods_document.create_end")' class="qf_date"
                              @change="dataPost(rangeTimeTwo, 'createdrang')" :format="format"
                              value-format="YYYY-MM-DD" />
                          </el-form-item>
                        </el-col>






                       












                      </el-row>

                    </el-form>
                    <!-- 表单 -->
                  </div>
                </el-scrollbar>
              </div>
              <div class="modal-footer">
                <!-- 取消 -->
                <el-button type="default" @click="closeModal(searchFormRef)">{{ $t("merak.reset")
                  }}</el-button>
                <!-- 搜索 -->
                <el-button type="primary" @click="submitForm(searchFormRef)">{{ $t("merak.search")
                  }}</el-button>
                <!-- 保存搜索方案 -->
                <el-button plain type="primary" v-if="searchProp.closePlan" @click="showPlanModal">
                  {{ $t("merak.save_search_scheme") }}
                </el-button>
              </div>
            </div>
            <!--  高级搜索弹出框内容-->
          </template>
          <!-- /高级搜索弹出框 插槽-->

















          <template #footer>
            <el-button v-auth="{ authArr: authArr, key: 'add' }" type="primary" @click="addmerge_btn_open()">
              {{$t("goods_document.add_document")}}
            </el-button>
          </template>
        </searchBar>
      </div>
      <div class="merak-table-wrapper">
        <MerakXTable ref="tableRef" :columns-by-store="JSON.parse(JSON.stringify(state.columns))"
        v-bind="tableState"
          :query-columns="handleQueryColumns" :query-data="handleQueryData" :params="state.params"
          :column-min-width="120" :column-type="columnTypeArr" :data="state.data" :batch-click="handleBatchClick"
           :await-params="true" :handler-click="handleHandlerClick" :enabled-editor="tableEditorAuth"
          @editor-click="handleEditorClick">
          <template #custom_handle="{ row }">
            <el-button type="primary" 
            v-auth="{ authArr: authArr, key: 'edit' }"
            link @click="
        router.push({ name: 'goodsDocumentCard', query: { id: row?.goods_certify_id, name: row?.goods_certify_no } })

        ">
             {{ $t("merak.detail") }}
            </el-button>

            <el-button
            v-auth="{ authArr: authArr, key: 'add' }"
              type="primary"
              link
            
              @click="copyFun(row?.goods_certify_id)"
            >
            {{ $t("merak.copy") }}
            </el-button>

             <el-button
             v-auth="{ authArr: authArr, key: 'del' }"
              :type="row.allow_delete?'default':'danger'"
              link
              :disabled="row.is_disable"
              @click="delFun(row?.goods_certify_id)"
            >
              {{ $t("merak.delete") }}
            </el-button>





          </template>

          <template #sp_type_slots="{ row }">
            <span :style="`color:${row.color}`"> <i class="dian" :style="`background:${row.color}`"></i>{{ row.sp_type
              }} </span>
          </template>
        </MerakXTable>
      </div>
    </div>
    <!-- 查看详情start -->

    <Transition name="fade" mode="out-in">
      <AddCard v-if="addmerge_btn"  :goodsId="goodsId" :typeId="cur_type" @close="(refresh, typeId) => handleClose(refresh, typeId)" />
    </Transition>

    <div>
      <el-drawer append-to-body v-model="showRemainingModal">
        <template #header>「{{ xqtitle }}」{{ $t("goods_attribute.mjkey") }}</template>
        <div class="export">
          <el-button v-auth="{ authArr: authArr, key: 'mergeexport' }" size="small" link @click="handleExport">{{
        $t("merak.export_data")
      }}</el-button>
        </div>
        <el-table class="merak-table-container" v-loading="xqloading" max-height="calc(100vh - 140px)" :data="xqfrom">
          <el-table-column prop="merge_propvalue_id" label="属性ID" />
          <el-table-column prop="merge_propvalue_cn" :label="$t('goods_allocation_merge.merge_prop_cn')" />
          <el-table-column prop="merge_propvalue_ru" :label="$t('goods_allocation_merge.merge_prop_ru')" />
          <template #empty>
            <div v-if="xqfrom" style="padding: 100px 40px 0">
              <img :src="EmptyPng" style="object-fit: cover; height: 130px" />
            </div>
          </template>
        </el-table>
      </el-drawer>

      <el-dialog v-model="edit_model" :width="500" align-center append-to-body>
        <template #header>
          <div class="editor-title">{{ $t("merak.edit") }}「{{ $t(`goods_allocation_merge.${edit_modal_arr.curField}`)
            }}」</div>
        </template>
        <el-form ref="formRef" label-position="top" :model="edit_modal_arr">
          <el-input v-model="edit_modal_arr.curval" class="qf_input" />
        </el-form>
        <template #footer>
          <el-button @click="edit_model = false">{{ $t("merak.cancel") }}</el-button>
          <el-button :disabled="edit_disabled" :loading="edit_loading" type="primary" @click="tdSave(edit_modal_arr)">{{
        $t("merak.confirm")
            }}</el-button>
        </template>
      </el-dialog>
    </div>
    <!-- 查看详情end -->
  </div>
</template>

<script lang="ts" setup name="goods_document">
import useDateFormat from "@/hooks/useDateFormat";
import AddCard from "./AddCard.vue";

import { Plus, Edit, Delete, EditPen, Search } from "@element-plus/icons-vue";
import { useDefaultStore } from "@/stores/modules/default";
import { ref, reactive, onMounted, getCurrentInstance, computed } from "vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import EmptyPng from "@/assets/images/empty.png";
import searchBar from "@/components/SearchBar";
import merakColapse from "@/components/merakColapse/index.vue";
import selectedParams from "@/components/SearchBar/components/selectedParams.vue";
import { exportTableApi } from "@/api/modules/table";
import { useRoute, useRouter } from "vue-router";

import MerakXTable, {
  MerakXTableInstance,
  MerakXTableColumn,
  MerakXTableProps,
  MerakXTableQuery
} from "@/components/MerakXTable";

import {
  getLeftApi,
  getmergeDataApi,
  getmergfieldApi,
  updatamergfieldApi,
  gatEnmuApi,
  mergePropdelete,
  getoptionApi
} from "@/api/modules/goodsArchive/documentList";

import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";
import { useGlobalStore } from "@/stores/modules/global";

import treeNode from "@/views/personalManagement/a-components/oragnizationTree/index.vue";
import { getLocationParams } from "@/utils/index";

import type { ElForm } from "element-plus";
import I18n from "@/languages/index";
import { watch } from "vue";

const $t = I18n.global.t;

const lang = ref("");
lang.value = $t("lang");
const columnTypeArr = ref([{ type: 'handle', width: lang=='ru'?300:200, slot: 'custom_handle' }]);
const route = useRoute();
const router = useRouter();

const defaultStore = useDefaultStore();
const edit_disabled = ref(false);
const edit_loading = ref(false);

const pageloading = ref(false);


// consumer = "consumer", //消费品
// industrial = "industrial", //工业品
// food = "food" //食品

const { format } = useDateFormat();
type FormInstance = InstanceType<typeof ElForm>;
const leavesRef = ref<FormInstance>();

const { proxy } = getCurrentInstance();

// const curMergeType = ref("sale");
// const ownAllType = [
//   { value: "sale", label: "日用品" },
//   { value: "mro", label: "工业品" },
//   { value: "food", label: "食品" }
// ];
const addmerge_btn = ref(false);
const cur_type = ref("");

//   打开添加窗口
const addmerge_btn_open = async e => {
  console.log(cur_type.value);

  addmerge_btn.value = true;
};

const tableRef = ref<MerakXTableInstance>();

//批量操作
const handleBatchClick = async e => { };

// 关闭添加页面
const handleClose = (refresh: boolean, typeId) => {
  console.log(typeId);

  if (refresh) {
    if (cur_type.value == typeId) {
      console.log("相等只刷新右侧");
    } else {
      console.log("不相等刷新所有");
      getLeftFun("sale");
      // curMergeType.value = "sale";
    }
    // 因为左侧树已经被选择了  因此任何情况下都刷新列表
    tableRef.value?.reloadData();
  }
  addmerge_btn.value = false;
};

//#region 搜索表单
const search_val = ref("");
const searchFn = e => {
  console.log(e);
  // e.searchVal
  state.params.key_words = e.search;
};

const expandedKeys = ref([]);


// 树点击
const changeTreeFilter: InstanceType<typeof ElTree>["onCurrent-change"] = (data, treeNode) => {
  if (!treeNode.isLeaf) return;
  //   const url = new URL(location.href);
  //   if (data.id === "all") {
  //     url.searchParams.delete("key");
  //   } else {
  //     url.searchParams.set("key", data.id.toString());
  //   }
  // //   treeState.value = data.value.toString();
  //   // 记录浏览器参数
  //   history.pushState({}, "", url);

  console.log(data)
  curcheck_id.value = [data.id];
  treeRef.value?.setCheckedKeys([data.id]);





  console.log(cur_type.value);

  if (data.id.indexOf("-") > -1) {
    var newarr = data.id.split("-");
    cur_type.value = newarr[1];
  } else {
    cur_type.value = data.id;
  }
  console.log(cur_type.value);

  state.params.type_id = cur_type.value;
  searchbar.value.clear();
  state.params.keyword = "";
};

const curlevel = ref(1);

//权限数据
let authArr = ref({});

//列表内容展示区
const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
  const params: Record<string, any> = {};
  if (!!page) {
    // if (curcheck_id.value[0].indexOf('-') > -1) {
    // 	var newarr = curcheck_id.value[0].split('-');
    // 	cur_type.value = newarr[1]

    // } else {
    // 	cur_type.value = curcheck_id.value[0];
    // }

    Object.assign(params, { ...page, type_id: cur_type.value, keyword: params.search });
  }
  // console.log(from)
  for (let key of Object.keys(from)) {
    if (!!from[key] || typeof from[key] === 'number') {
      params[key] = from[key];
    }
  }
  return await getmergeDataApi(params).then(res => {
    // console.log(res)
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data;
      Object.assign(authArr, data.auth_list);

      // 权限02
      authArr.value = res.auth_list;
      if (authArr.value?.del.show == false && authArr.value?.edit.show == false  ) {
        
        columnTypeArr.value=[];
        
      }

      const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };
      return table_data;
    }
  });
};

const showRemainingModal = ref(false);
const showRemainingData = ref([]);
const xqfrom = ref();
const xqloading = ref(false);
const xqtitle = ref();
const { language } = useGlobalStore();
const xq_merge_prop_id = ref("");
const xq_table_id = ref("");

//打开查看请假详情
const showRemaining = (merge_prop_id, title) => {
  xqtitle.value = title;
  console.log(merge_prop_id);
  xq_merge_prop_id.value = merge_prop_id;
  xqloading.value = true;
  showRemainingModal.value = true;

  gatEnmuApi({ merge_prop_id: merge_prop_id }).then(res => {
    xqloading.value = false;
    if (res.code == ResultEnum.SUCCESS) {
      xqfrom.value = res.data.table_data.list;
      xq_table_id.value = res.data.table_id;
      // showRemainingData.value = list;
    }
  });
};
const handleExport = () => {
  if (typeof xq_merge_prop_id.value === "undefined" || typeof xq_merge_prop_id.value === "undefined") return;
  // 关闭下载列表
  defaultStore.downVisable = false;

  exportTableApi({
    table_id: xq_table_id.value,
    route_name: `${xqtitle.value}枚举值`,
    route_condition: { merge_prop_id: xq_merge_prop_id }
  }).then(({ code, message }) => {
    if (code == ResultEnum.SUCCESS) {
      showRemainingModal.value = false;
      defaultStore.downVisable = true;
    } else {
      failMsg(res.message);
    }
  });
};

// 单元格编辑保存
const tdSave = row => {
  edit_disabled.value = true;
  edit_loading.value = true;
  updatamergfieldApi({ merge_prop_id: row.rowKey, field: row.curField, value: row.curval }).then(res => {
    edit_disabled.value = false;
    edit_loading.value = false;
    if (res.code == ResultEnum.SUCCESS) {
      edit_model.value = false;
      tableRef.value?.reloadData();
    } else {
      failMsg(res.message);
    }
  });
};

// 表格相关属性
const tableState = reactive<MerakXTableProps>({
  columnsByStore: [],
  rowKey: "goods_certify_id",
  columnType: [{ type: "handle", width: 130, showHandleDropDown: true, slot: "custom_handle" }],
  handles: [
    { type: "copy", text: "复制" },
    { type: "delete", text: $t("merak.delete"), color: "red" }
  ]
});


const goodsId=ref('')

// 操作列下拉选项点击事件
const handleHandlerClick: MerakXTableProps["handlerClick"] = async ({ type, params }) => {
  const propId = params.row?.[tableState.rowKey!];
  // const typeId = params.row?.type_id_val;
  // if (typeof propId === "undefined" || typeof typeId === "undefined") return;
  console.log(params);
  switch (type) {
    case "copy":
     
       console.log("复制"+propId)
 


      break;
    case "delete":
      console.log("删除");
      
      
      break;
    default:
      break;
  }
};

const copyFun = (propId) => {
  addmerge_btn.value = true;
      goodsId.value=propId;
}

const delFun = (propId) => {

  confirmWarningMsg({
        msg: $t("goods_document.is_del_tip") ?? "",
        callback: (status: string) => {
          if (status === "confirm") {
            pageloading.value=true;
            mergePropdelete({ goods_certify_id: propId }).then(({ code, message }) => {
              pageloading.value=false;
              if (code == ResultEnum.SUCCESS) {
                tableRef.value?.reloadData();
                successMsg($t("goods_attribute.delete_property_success"));
              } else {
                failMsg(message);
              }
            });
          }
        }
      });
}



const queryFilterOptions = async data => {
  searchbar.value.getPlanList(data.table_id);
  // 初始化接口需要传入队列 loading 暴露的 id
};

//表头信息
const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
  return await getmergfieldApi().then(res => {
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data as MerakXTableQuery.Columns;
      // 克隆表头数据作为列设置的对照数据
      tableState.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      data.columns.map(column_ever => {
        console.log(column_ever);
        if (column_ever.field == "merge_prop_cn" || column_ever.field == "merge_prop_ru") {
          column_ever["params"] = { editor: true };
        } else {
          column_ever["params"] = { editor: false };
        }
      });

      console.log(data.columns);
      queryFilterOptions(data);
      state.columns = data.columns;
      return data;
    }
  });
};

interface Tree {
  label: string;
  children?: Tree[];
}

const handleNodeClick = (data: Tree) => {
  console.log(data);
};
const defaultKey = ref(1);
const treedata: Tree[] = ref([]);

const defaultProps = {
  children: "childs",
  label: "label"
};
const treeFilter = ref("");
const treeRef = ref();

const state = reactive<{
  params: Record<string, any>;
  columns: MerakXTableColumn[];
}>({
  params: {
    key_words: ""
  },
  columns: []
});

//触发了快速搜索或者搜索方案
// const searchBarPost = params => {
//   // console.log(params)

//   let postParams = { ...params.params, keyword: params.search };
//   state.params = postParams;
// };

// 编辑表格
// 给予表格编辑权限

//   获取左侧数据
const curcheck_id = ref([]);
const getLeftFun = type => {
  getLeftApi().then(res => {
    if (res.code == ResultEnum.SUCCESS) {
      for (let index = 0; index < res.data.length; index++) {
        const element = res.data[index];
        element["id"] = element.value + "";
        if (element.childs) {
          for (let index = 0; index < element.childs.length; index++) {
            const son_element = element.childs[index];
            son_element["id"] = element.value + "-" + son_element.value;
          }
        }
      }






      treedata.value = res.data;
      console.log(treedata.value)
      treedata.value.unshift({ "label": $t("merak.all"), value: "0", id: "0" })
      treeRef.value?.setCheckedKeys(['0']);
      if (treedata.value.length > 0) {

        expandedKeys.value = [treedata.value[0].value];
      } else {
        treedata.value = [{ value: "" }];
      }

      curcheck_id.value = ["0"]
      console.log(curcheck_id.value);

      if (curcheck_id.value[0].indexOf("-") > -1) {
        var newarr = curcheck_id.value[0].split("-");
        cur_type.value = newarr[1];
      } else {
        cur_type.value = curcheck_id.value[0];
      }

      if (res.data.length < 1) {
        cur_type.value = "-1";
      }

      state.params.type_id = cur_type;
    } else {
      failMsg(res.message);
    }
  });
};

onMounted(async () => {
  getLeftFun("sale");
});

const edit_model = ref(false);
const editForm = ref({
  aaa: "",
  bbb: ""
});
const tableEditorAuth = computed(() => {
  let flag = false;

  if (!!authArr.value?.mergeCard?.show) {
    flag = true;
  }
  return flag;
});

// 切换左侧商品类型
// const change_prop_type = id => {
//   console.log(id);
//   getLeftFun(id);
//   searchbarRef.value.clear();
// };

const edit_modal_arr = ref({ curField: "", curval: "", rowKey: "" });

// 表格编辑事件
const handleEditorClick: MerakXTableInstance["onEditor-click"] = params => {
  console.log(params);
  edit_model.value = true;
  edit_modal_arr.value.curField = params.field;
  edit_modal_arr.value.rowKey = params.rowKey;
  edit_modal_arr.value.curval = params.value;
};









// 高级搜索
// 高级搜索表单
const searchFormRef = ref<FormInstance>();
const searchform = reactive({











  goods_certify_no: {
    label:$t("goods_document.goods_certify_no"),
    value: ""
  },
  product_description: {
    label: $t("goods_document.product_description"),
    value: ""
  },
  other_brands: {
    label: $t("goods_document.other_brands"),
    value: ''
  },

  daterang: {
    label: $t("goods_document.period_date_valid"),
    value: ''
  },

  createdrang: {
    label: $t("goods_document.create_time"),
    value: ''
  },




  goods_certify_type: {
    label:$t("goods_document.goods_certify_type"),
    value: "",
    type: "select",
    options: []
  },
  apply_name_factory: {
    label: $t("goods_document.apply_name_factory"),
    value: "",
    type: "select",
    options: []
  },
  invalid: {
    label: $t("goods_document.invalid"),
    value: "",
    type: "select",
    options: []
  },
  adult_child: {
    label:$t("goods_document.adult_child"),
    value: "",
    type: "select",
    options: []
  },
  apply_type: {
    label: $t("goods_document.apply_type"),
    value: "",
    type: "select",
    options: []
  },
  factoy: {
    label: $t("goods_document.factoy"),
    value: "",
    type: "select",
    options: []
  },
  type_id: {
    label: $t("goods_document.type_id"),
    value: "",
    type: "select",
    options: []
  },
  created_by: {
    label: $t("goods_document.created_by"),
    value: "",
    type: "select",
    options: []
  },
  supplier_id: {
    label: $t("goods_document.supplier_id"),
    value: "",
    type: "select",
    options: []
  },
  brand: {
    label: $t("goods_document.brand"),
    value: "",
    type: "select",
    options: []
  },



});


const rangeTimeOne = ref([]);
const rangeTimeTwo = ref([]);



watch(searchform.daterang, val => {
  if (!searchform.daterang.value) {
    rangeTimeOne.value = [];
  }
});
watch(searchform.createdrang, val => {
  if (!searchform.createdrang.value) {
    rangeTimeTwo.value = [];
  }
});












// 高级搜索表单验证
const searchformRules = reactive({


  "goods_certify_type": [], //单证类型
  "apply_name_factory": [], //进口公司
  "invalid": [],  //单证状态
  "adult_child": [],//年龄
  "apply_type": [],// 申请人
  "factoy": [],  //中国公司
  "type_id": [],//商品类型
  "created_by": [], //创建人
  "supplier_id": [], //商家
  "brand": [],//品牌


  "goods_certify_no": [], //注册编号
  "product_description": [],  //商品描述
  "other_brands": [],   //其他品牌
  start_date: [],
  end_date: [],
  "created_at_start": [],
  "created_at_end": []




});

const dataPost = (val, key) => {
  // console.log(params)

  searchform[key].value = val[0] +' '+ $t("merak.rangto")+' ' + val[1];


  // let postParams = { ...params.params, search: state.params.search, begin_date: rangeTime.value[0], end_date: rangeTime.value[1] };
  // state.params = postParams;
};


//高级搜索模态
const searchbar = ref();


//触发了快速搜索或者搜索方案
const searchBarPost = params => {
  let postParams = { ...params.params, key_words: params.search };
  state.params = postParams;
};

//点击取消按钮关闭高级搜索模态框
const closeModal = (formEl: FormInstance | undefined) => {
  searchFormRef.value?.resetFields();
  searchbar.value.modalHide();
  searchbar.value.clear();


  // searchform.employee_name.value = "";
  // searchform.job_number.value = '';
  // rangeTime.value = ['', ''];
  // searchform.type.value = '';



  for (var i in searchform) {
    console.log(i, ":", searchform[i]);
    if (i == 'createdrang' || i == 'daterang') {
      searchform[i].value = '';
    } else {
      searchform[i].value = ''
    }
  }











  state.params = {};
};

//打开搜索方案弹出
const showPlanModal = () => {
  searchbar.value.showPlanModal();

};

const optionloading = ref(false);

const handleVisibleChange = (options, key) => {
  console.log(options, key)
  if (options.length === 0) {
    console.log("111111")
    optionloading.value = true;
    getoptionApi({ key: key }).then(res => {
      optionloading.value = false;
      if (res.code == ResultEnum.SUCCESS) {

        searchform[key].options = res.data;

      } else {
        failMsg(res.message);
      }
    });

  }
};


//搜索表单提交
const submitForm = async (formEl: FormInstance | undefined) => {

  search_val.value = "";
  let postParams = {
    "goods_certify_type": searchform.goods_certify_type.value, //单证类型
    "apply_name_factory": searchform.apply_name_factory.value, //进口公司
    "invalid": searchform.invalid.value,  //单证状态
    "adult_child": searchform.adult_child.value,//年龄
    "apply_type": searchform.apply_type.value,// 申请人
    "factoy": searchform.factoy.value,  //中国公司
    "type_id": searchform.type_id.value,//商品类型
    "created_by": searchform.created_by.value, //创建人
    "supplier_id": searchform.supplier_id.value, //商家
    "brand": searchform.brand.value,//品牌


    "goods_certify_no": searchform.goods_certify_no.value, //注册编号
    "product_description": searchform.product_description.value,  //商品描述
    "other_brands": searchform.other_brands.value,   //其他品牌
    start_date: rangeTimeOne.value[0],
    end_date: rangeTimeOne.value[1],
    "created_at_start": rangeTimeTwo.value[0],
    "created_at_end": rangeTimeTwo.value[1],

  };
  state.params = postParams;

  searchbar.value.clear();
  searchbar.value.modalHide();
};




















</script>

<style scoped lang="scss">
:deep(.merak_modal.xq .el-form .el-form-item__label) {
  justify-content: flex-end;
}

.merak-aside {
  display: flex;
  flex-direction: column;

  .tree-wrapper {
    flex: 1;
    min-height: 0;
  }
}

.el-tree {
  :deep(.el-tree-node.is-checked .el-tree-node__content:has(.is-leaf)) {
    color: #fff !important;
    background-color: var(--el-color-primary) !important;
  }
}

.translation {
  /* display: flex;
			flex-direction: column;
			width: 100%;*/
  height: 100%;
}

.translation_card {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;

  .table_main {
    /* display: flex;
				flex-direction: column;
				width: 100%;
				height: 100%; */
    flex: auto;
    min-height: 0;
  }
}

.translationPad {
  padding: 15px;
}

.dian {
  display: inline-block;
  width: 4px;
  height: 4px;
  border-radius: 50px;
  background-color: #fff;
  margin-right: 6px;
  position: relative;
  top: -2px;
}

.export {
  margin-bottom: var(--merak-space);
  text-align: right;
}

.xq .el-form-item__content {
  color: #303133;
  font-size: 13px;
}

:deep(.el-form-item__label) {
  padding-right: 40px;
}

:deep(.noCurCss.filter .el-scrollbar .el-tree--highlight-current .el-tree-node.is-current .el-tree-node__content) {
  background-color: #fff;
  color: var(--el-tree-text-color);
}

:deep(.noCurCss.filter .el-scrollbar .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content .el-tree-node__label,
  .noCurCss.filter .el-scrollbar .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content .el-tree-node__expand-icon) {
  color: var(--el-tree-text-color);
}

:deep(.flx-justify-between.header) {
  display: none;
}

.merak-container-has-aside {
  position: relative;
}
</style>
